import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {SharedModule} from '../shared.module';
import areas from '../../const/area.json'
import {CaptchaComponent} from '../captcha/captcha.component';
import {TITLE} from '../../const';
import {CandidateForm} from '../../types/req/CandidateForm';
import {CandidateService} from '../../service/candidate.service';
import {Router} from '@angular/router';

@Component({
  selector: 'job-seeker-register',
  imports: [    
    SharedModule,
    CaptchaComponent
  ],
  templateUrl: './job-seeker-register.component.html',
  standalone: true,
  styleUrls: ['../../assets/register.less']
})
export class JobSeekerRegisterComponent implements OnInit {
  jobSeekerToSave:CandidateForm = {};
  jobSeekerRegisterForm!: FormGroup;
  verificationCode: string = '';
  saveLoading: boolean = false
  title: string = TITLE
  jobSeekerRegisterTitle: string = '教师注册'
  provinceCityAreaOptions = areas.provinces;

  @Output() addedEvent = new EventEmitter<boolean>();

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private candidateService: CandidateService,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.jobSeekerRegisterForm = this.fb.group({
      username: ['', [Validators.required]],
      name: ['', [Validators.required]],
      password: ['', [Validators.required]],
      password2: ['', [Validators.required]],
      gender: [undefined, [Validators.required]],
      birthDate: ['', [Validators.required]],
      contactPhone: ['', [Validators.required]],
      email: ['', [Validators.required]],
      province: [''],
      city: [''],
      area: [''],
      provinceCityArea: [[]],
      address: [''],
      verificationCode: ['', [Validators.required]],
    })
  }

  onSave() {
    try {
      this.saveLoading = true
      for (const i in this.jobSeekerRegisterForm.controls) {
        this.jobSeekerRegisterForm.controls[i].markAsDirty();
        this.jobSeekerRegisterForm.controls[i].updateValueAndValidity();
      }
      if (!this.jobSeekerRegisterForm.valid) {
        this.saveLoading = false
        return
      }
      const formValue = this.jobSeekerRegisterForm.value;
      if (formValue.password.toLowerCase() !== formValue.password2.toLowerCase()) {
        this.message.error('两次输入的密码不一致，请重新输入');
        this.onReset()
        this.saveLoading = false
        return
      }
      if (formValue.verificationCode.toLowerCase() !== this.verificationCode.toLowerCase()) {
        this.message.error('验证码错误');
        this.onReset()
        this.saveLoading = false
        return
      }
      this.candidateService.save(Object.assign(this.jobSeekerToSave, formValue)).subscribe({
        next: (resp: any) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          this.message.success("保存成功")
          this.router.navigate(['/login'], { queryParams: { type: 3 } })
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onReset() {
    this.jobSeekerRegisterForm.reset()
    this.jobSeekerRegisterForm.patchValue({
      provinceCityArea: []
    })
  }

  onBack() {
    this.router.navigate(['/login'], { queryParams: { type: 3 } })
  }


  onVerificationCodeGenerated(verificationCode: string): void {
    this.verificationCode = verificationCode
  }
}
